﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Xml.Serialization;
using System.IO;


namespace MergerProject
{

    public class Merger2012 : IMerger
    {

        /// <summary>
        /// tfssrv1:8080/tfs/defaultcollection
        /// </summary>

        public TfsTeamProjectCollection teamProjectCollection = null;
        public WorkItemCollection wiCollection = null;
        public List<FilteredWorkItemChangests> fwicList = null;
        VersionControlArtifactProvider artifactProvider = null;
        VersionControlServer versionControlServer = null;
        public Project project = null;
        public WorkItemStore workItemStore = null;



        public string sourceBranchName = string.Empty;
        public string targetBranchName = string.Empty;
        public string sourceBranchServerPath = string.Empty;
        public string targetBranchServerPath = string.Empty;
        public DataTable projectListTable;
        public List<BranchObject> branchList = new List<BranchObject>();

        public Workspace sourceWorkspace = null;
        public Workspace destWorkspace = null;


        public string mergeLog = string.Empty;

        public DataTable serverTable = null;
        public RegisteredProjectCollection[] registeredProjectCollection;
        public RegisteredProjectCollection selectedProjectCollection;
        public ProjectInfo[] projectList = null;
        public TfsConfigurationServer serverConfig = null;

        public delegate void PendingChangesDelegate(string text, bool clear, string comment, string workitemid);
        public delegate void LoggerDelegate(string text);
        static public LoggerDelegate _loggerDelegate;
        static public PendingChangesDelegate _pendingChangesDelegate;
        public PendingChange[] waitingChanges = null;


        public delegate void conflictsDelegate(string text, bool clear);
        static public conflictsDelegate _conflictsDelegate;

        public DataTable GetServers()
        {
            try
            {

                serverTable = new DataTable();
                serverTable.Columns.Add("Name");
                serverTable.Columns.Add("Url");

                if (registeredProjectCollection != null && registeredProjectCollection.Count() > 0)
                {
                    foreach (var item in registeredProjectCollection)
                    {
                        DataRow drow = serverTable.NewRow();
                        drow[0] = item.Name;
                        drow[1] = item.Uri;
                        serverTable.Rows.Add(drow);

                    }
                }
                else if (myCustomServerList != null && myCustomServerList.serverList != null)
                {
                    foreach (var item in myCustomServerList.serverList)
                    {
                        DataRow drow = serverTable.NewRow();
                        drow[0] = item.TfsUrl;
                        drow[1] = item.TfsUrl;
                        serverTable.Rows.Add(drow);

                    }
                }

                return serverTable;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " " + ex.StackTrace);
            }

            return serverTable;
        }
        public Merger2012()
        {

        }



        public void Initialize(string url, string defaultProjectName)
        {


            bool serverFounded = false;
            bool projectFounded = false;

            registeredProjectCollection = RegisteredTfsConnections.GetProjectCollections();

            if ((registeredProjectCollection == null || registeredProjectCollection.Count() == 0) && myCustomServerList != null && myCustomServerList.serverList != null)
            {
                foreach (var item in myCustomServerList.serverList)
                {
                    RegisteredTfsConnections.RegisterProjectCollection(TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
                       new Uri(item.TfsUrl)));
                }

            }

            registeredProjectCollection = RegisteredTfsConnections.GetProjectCollections();

            if (registeredProjectCollection != null && registeredProjectCollection.Count() > 0)
            {

                foreach (var item in registeredProjectCollection)
                {
                    if (item.Uri.AbsoluteUri.Contains(url))
                    {
                        selectedProjectCollection = item;
                        serverFounded = true;
                        break;
                    }
                }

                if (!serverFounded)
                {
                    selectedProjectCollection = registeredProjectCollection.First();
                }

                teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(selectedProjectCollection);

            }
            else if (myCustomServerList != null && myCustomServerList.serverList != null && myCustomServerList.serverList.Count > 0)
            {


                foreach (var item in myCustomServerList.serverList)
                {
                    if (item.TfsUrl.Contains(url))
                    {
                        teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
                 new Uri(item.TfsUrl));
                        serverFounded = true;
                        break;
                    }
                }

                if (teamProjectCollection == null)
                    teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
     new Uri(myCustomServerList.serverList.First().TfsUrl));

            }



            ICommonStructureService structureService = (ICommonStructureService)teamProjectCollection.GetService(typeof(ICommonStructureService));
            projectList = structureService.ListAllProjects();

            foreach (var item in projectList)
            {
                if (item.Name == defaultProjectName)
                {
                    projectFounded = true;
                    break;
                }
            }

            if (!projectFounded)
            {

                defaultProjectName = projectList.First().Name;
            }



            tfsUrl = teamProjectCollection.Uri.AbsoluteUri;

            teamProjectCollection.Authenticate();
            workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));
            versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
            artifactProvider = versionControlServer.ArtifactProvider;

            if (string.IsNullOrEmpty(defaultProjectName))
            {
                selectedProjectName = projectList[0].Name;
            }
            else
                selectedProjectName = defaultProjectName;

        }


        public string getUserName()
        {
            return teamProjectCollection.AuthorizedIdentity.DisplayName;
        }
        public object GetWorkItemListFromWorkItemIds(List<string> workItemIDList)
        {
            WorkItemCollection witemColl = null;

            //
            string query = "select[System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State] from WorkItems where [System.TeamProject] = '" + selectedProjectName + "' and [System.WorkItemType] <> '' and [System.State] <> '15-Production (Closed)'  and [System.ID] In({0}) order by[System.Id]";

            // Get atest for sourcebranch
            GetRequest request = new GetRequest(new ItemSpec(sourceBranchServerPath, RecursionType.Full), VersionSpec.Latest);
            sourceWorkspace.Get(request, GetOptions.None); // this line doesn't do anything - no failures or errors

            // Get latest for destintion branch
            request = new GetRequest(new ItemSpec(targetBranchServerPath, RecursionType.Full), VersionSpec.Latest);
            destWorkspace.Get(request, GetOptions.None); // this line doesn't do anything - no failures or errors

            string workItems = string.Empty;
            foreach (var item in workItemIDList)
            {
                if (!string.IsNullOrEmpty(workItems))
                    workItems += ",";

                workItems += item;

            }

            QueryDefinition myQuery = new QueryDefinition("CustomQuery", string.Format(query, workItems));

            if (myQuery != null)
            {

                witemColl = workItemStore.Query(myQuery.QueryText);
            }

            return witemColl;

        }

        public List<FilteredWorkItemChangests> getWorkItemsChangeSetList(object _workItemCollection)
        {

            List<FilteredWorkItemChangests> _fwicList = new List<FilteredWorkItemChangests>();
            foreach (WorkItem workItem in (WorkItemCollection)_workItemCollection)
            {
                FilteredWorkItemChangests fwic = new FilteredWorkItemChangests();
                fwic.workitemID = workItem.Id.ToString();
                fwic.workitemDesc = workItem.Title.ToString();

                /// get changeset list related with workitem
                /// ......................................................................
                Changeset[] changeSetlist = workItem.Links
                       .OfType<ExternalLink>()
                       .Select(link => artifactProvider
                           .GetChangeset(new Uri(link.LinkedArtifactUri))).ToArray();
                ///........................................................................

                foreach (var changeset in changeSetlist)
                {
                    bool hasMerged = false;
                    bool inSourceBranch = false;

                    if ((changeset.Changes[0].Item.ItemType == Microsoft.TeamFoundation.VersionControl.Client.ItemType.File || changeset.Changes[0].Item.ItemType == Microsoft.TeamFoundation.VersionControl.Client.ItemType.Folder) && (changeset.Changes[0].Item.ServerItem.Contains(sourceBranchServerPath) || changeset.Changes[0].ChangeType == Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Delete))
                    {
                        inSourceBranch = true;
                        List<string> branches = new List<string> { targetBranchServerPath };
                        var merges = versionControlServer.TrackMerges(new int[] { changeset.ChangesetId },
    new ItemIdentifier(sourceBranchServerPath),
    branches.Select(b => new ItemIdentifier(b)).ToArray(),
    null);
                        if (merges.Count() > 0)
                        {
                            hasMerged = true;
                            //foreach (ExtendedMerge item in merges)
                            //{

                            //    var rs = changeSetlist.Where(a => a.ChangesetId == item.TargetChangeset.ChangesetId);
                            //    if (rs.Count() > 0 && item.TargetItem.Item.Contains(targetBranchServerPath))
                            //        hasMerged = true;
                            //}

                        }
                    }

                    if (!hasMerged && inSourceBranch)
                        fwic.changeSetList.Add(changeset);
                }

                _fwicList.Add(fwic);
            }

            return _fwicList;
        }

        public void FillMergeTable()
        {
            wiCollection = GetWorkItemListFromWorkItemIds(workItemIDs) as WorkItemCollection;
            fwicList = getWorkItemsChangeSetList(wiCollection);
            mergeTable = GetMergeChangeSetTable();
            changeSetDetailsTable = GetMergeChangeSetDetailTable();
            foreach (FilteredWorkItemChangests item in fwicList)
            {

                for (int i = 0; i < item.changeSetList.Count; i++)
                {
                    Changeset changeset = item.changeSetList[i] as Changeset; ;
                    DataRow drow = mergeTable.NewRow();
                    drow["WorkitemId"] = item.workitemID;
                    drow["ChangeSetID"] = changeset.ChangesetId;
                    drow["Title"] = changeset.Comment;
                    drow["Merged"] = "False";
                    drow["CheckInDate"] = string.Format("{0:dd.MM.yyyy HH:mm:ss}", changeset.CreationDate);
                    drow["User"] = changeset.OwnerDisplayName;


                    string changesetid = changeset.ChangesetId.ToString();
                    for (int x = 0; x < changeset.Changes.Count(); x++)
                    {
                        DataRow detailRow = changeSetDetailsTable.NewRow();
                        detailRow[0] = changesetid;
                        detailRow[1] = changeset.Changes[x].Item.ServerItem;
                        detailRow[2] = changeset.Changes[x].ChangeType.ToString();
                        changeSetDetailsTable.Rows.Add(detailRow);
                    }

                    if (drow[0] != null && !string.IsNullOrEmpty(drow[0].ToString()))
                        mergeTable.Rows.Add(drow);

                }

            }

            mergeTable.DefaultView.Sort = "ChangeSetID asc";
            mergeTable = mergeTable.DefaultView.ToTable(); ;



        }

        public DataTable GetMergeChangeSetTable()
        {
            DataTable dt = new DataTable("MergeTable");
            dt.Columns.Add("WorkitemId");
            dt.Columns.Add("ChangeSetID");
            dt.Columns.Add("Title");
            dt.Columns.Add("CheckInDate");
            dt.Columns.Add("User");
            dt.Columns.Add("Merged");
            return dt;
        }

        public DataTable GetMergeChangeSetDetailTable()
        {
            DataTable dt = new DataTable("MergeChangeSetDetail");
            dt.Columns.Add("ChangeSetID");
            dt.Columns.Add("FileName");
            dt.Columns.Add("CheckInType");
            return dt;
        }

        public void ShowResolveConflictsDlg(object wrkspc)
        {
            try
            {
                Assembly assres = Assembly.GetAssembly(typeof(Microsoft.TeamFoundation.VersionControl.Controls.ControlAddItemsExclude));
                var dlgResolveConflicts = assres.GetTypes().FirstOrDefault(x => x.Name == "DialogResolveConflicts");
                dlgResolveConflicts.InvokeMember("ResolveConflicts", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, new object[] { wrkspc, null, true, null });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        public void ShowResolveConflictsDlg()
        {
            try
            {
                Assembly assres = Assembly.GetAssembly(typeof(Microsoft.TeamFoundation.VersionControl.Controls.ControlAddItemsExclude));
                var dlgResolveConflicts = assres.GetTypes().FirstOrDefault(x => x.Name == "DialogResolveConflicts");
                dlgResolveConflicts.InvokeMember("ResolveConflicts", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, new object[] { destWorkspace, null, true, null });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            _conflictsDelegate.Invoke(string.Empty, true);

            Conflict[] conflicts = null;
            conflicts = destWorkspace.QueryConflicts(new string[] { targetBranchServerPath }, true);

            if (conflicts != null)
            {
                for (int i = 0; i < conflicts.Length; i++)
                {
                    _conflictsDelegate.Invoke(conflicts[i].ServerPath, false);
                }
            }
            else
            {
                _conflictsDelegate.Invoke(string.Empty, true);
            }
        }

        public DataTable getAllUsersTable()
        {
            IGroupSecurityService gss = teamProjectCollection.GetService<IGroupSecurityService>();

            Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, "Project Collection Valid Users", QueryMembership.Expanded);

            Identity[] UserId = gss.ReadIdentities(SearchFactor.Sid, SIDS.Members, QueryMembership.None);
            DataTable UserTable = new DataTable();
            UserTable.Columns.Add("UserID");
            UserTable.Columns.Add("UserName");

            foreach (Identity user in UserId)
            {
                if (user.Type == IdentityType.WindowsUser)
                {
                    DataRow drow = UserTable.NewRow();
                    drow[0] = user.AccountName;
                    drow[1] = user.DisplayName;
                    UserTable.Rows.Add(drow);
                }

            }

            if (UserId != null && UserId.Count() > 0)
            {
                UserTable.DefaultView.Sort = "UserName asc";
                UserTable = UserTable.DefaultView.ToTable();

            }

            return UserTable;


        }

        public DataTable getUserWorkItemListTable()
        {
            DataTable table = new DataTable();

            try
            {
                //
                string query = "select[System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State] from WorkItems where [System.TeamProject] = '" + selectedProjectName + "' and [System.WorkItemType] <> '' and [System.State] <> '15-Production (Closed)' and [System.ChangedBy] = '{0}'  order by[System.Id] desc";
                QueryDefinition myQuery = new QueryDefinition("CustomQuery", string.Format(query, selectedUser));

                if (myQuery != null)
                {

                    wiCollection = workItemStore.Query(myQuery.QueryText);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " " + ex.InnerException);
            }

            table.Columns.Add("wiid");
            table.Columns.Add("desc");

            for (int i = 0; i < wiCollection.Count; i++)
            {
                DataRow drow =
                table.NewRow();
                drow[0] = wiCollection[i].Id;
                drow[1] = wiCollection[i].Id + "=>" + wiCollection[i].Title;
                table.Rows.Add(drow);
            }

            return table;

        }



        public DataTable getProjectsDataTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            foreach (var item in projectList)
            {
                DataRow drow = dt.NewRow();
                drow[0] = item.Name;
                dt.Rows.Add(drow);
            }

            return dt;
        }

        public DataTable getBranchListTable()
        {

            var allBranches =
                   versionControlServer.QueryRootBranchObjects(RecursionType.Full);
            branchList = new List<BranchObject>();
            foreach (BranchObject brobj in allBranches)
            {
                if (brobj.Properties.RootItem.Item.Contains(selectedProjectName) && !brobj.Properties.RootItem.IsDeleted)
                {
                    branchList.Add(brobj);

                }
            }
            branchTable = new DataTable();
            branchTable.Columns.Add("Name");
            for (int i = 0; i < branchList.Count; i++)
            {
                DataRow drow = branchTable.NewRow();
                drow[0] = branchList[i].Properties.RootItem.Item.Substring(("$/" + selectedProjectName).Length + 1);
                branchTable.Rows.Add(drow);
            }

            return branchTable;

        }

        public void DetermineWorkSpaces(string sourceBranch, string destBranch)
        {

            WorkspaceInfo[] wrinf = Workstation.Current.GetAllLocalWorkspaceInfo();

            //   WorkspaceInfo
            //versionControlServer.TryGetWorkspace()

            for (int i = 0; i < wrinf.Length; i++)
            {
                try
                {
                    Workspace wrspace = wrinf[i].GetWorkspace(teamProjectCollection);
                    foreach (var item in wrspace.Folders)
                    {
                        if (item.ServerItem == ("$/" + selectedProjectName + "/" + sourceBranch) || item.ServerItem == ("$/" + selectedProjectName))
                        {
                            sourceWorkspace = wrspace;
                        }
                        if (item.ServerItem == ("$/" + selectedProjectName + "/" + destBranch) || item.ServerItem == ("$/" + selectedProjectName))
                        {
                            destWorkspace = wrspace;
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            }

            sourceBranchServerPath = "$/" + selectedProjectName + "/" + sourceBranch;
            targetBranchServerPath = "$/" + selectedProjectName + "/" + destBranch;

            sourceBranchName = sourceBranch;
            targetBranchName = destBranch;


        }

        public bool MergeChangeSet(string workItemId, string changeSetId, string comment, bool GetLatest)
        {
            bool merged = false;
            VersionSpec changesetToMerge = new ChangesetVersionSpec(changeSetId);

            if (GetLatest)
            {

                GetRequest request1 = new GetRequest(new ItemSpec(sourceBranchServerPath, RecursionType.Full), VersionSpec.Latest);
                sourceWorkspace.Get(request1, GetOptions.None); // this line doesn't do anything - no failures or errors

                GetRequest request = new GetRequest(new ItemSpec(targetBranchServerPath, RecursionType.Full), VersionSpec.Latest);
                destWorkspace.Get(request, GetOptions.None); // this line doesn't do anything - no failures or errors
            }


            // actually pend the merge

            GetStatus MergeStatus = destWorkspace.Merge(sourceBranchServerPath, targetBranchServerPath, changesetToMerge, changesetToMerge, LockLevel.None, RecursionType.Full, MergeOptions.None);
            mergeLog += "------------------------------------------------------------------------------------------------------";
            mergeLog += changesetToMerge + " merging...\r\n";
            mergeLog += "Number of Files: " + (MergeStatus.NumOperations + MergeStatus.NumConflicts).ToString() + "\r\n";
            mergeLog += "Number of Conflicts: " + MergeStatus.NumConflicts + "\r\n";
            mergeLog += "Number of Failures " + MergeStatus.NumFailures + "\r\n";
            mergeLog += "Number of auto resolved conflicts " + MergeStatus.NumResolvedConflicts + "\r\n";
            if (_loggerDelegate != null)
            {
                _loggerDelegate.DynamicInvoke(mergeLog);
                mergeLog = string.Empty;
            }
            Conflict[] conflicts = null;
            bool conflictOK = true;
            if (MergeStatus.NumConflicts > 0)
            {
                conflictOK = true;
                conflicts = destWorkspace.QueryConflicts(new string[] { targetBranchServerPath }, true);
                mergeLog += "Conflics resolving..." + "\r\n";
                destWorkspace.AutoResolveValidConflicts(conflicts, AutoResolveOptions.All);
                conflicts = destWorkspace.QueryConflicts(new string[] { targetBranchServerPath }, true);

                if (conflicts.Count() > 0)
                {
                    ShowResolveConflictsDlg(destWorkspace);
                    conflicts = destWorkspace.QueryConflicts(new string[] { targetBranchServerPath }, true);
                }

                if (conflicts.Count() > 0)
                    conflictOK = false;

                foreach (Conflict conflict in conflicts)
                {

                    mergeLog += conflict.LocalPath + " resolving..." + "\r\n";
                    mergeLog += "result :" + conflict.Resolution + "\r\n";

                }




            }

            PendingChange[] pendingChanges = destWorkspace.GetPendingChanges();
            List<PendingChange> pendingChangesList = pendingChanges.ToList<PendingChange>();
            List<PendingChange> deletependingChangesList = new List<PendingChange>();

            WorkItem workeditem = null;

            for (int t = 0; t < wiCollection.Count; t++)
            {
                if (wiCollection[t].Id.ToString() == workItemId)
                {
                    workeditem = wiCollection[t];
                    break;
                }
            }



            WorkItemCheckinInfo[] wrinfo = new WorkItemCheckinInfo[1];
            wrinfo[0] = new WorkItemCheckinInfo(workeditem, WorkItemCheckinAction.Associate);
            if (conflictOK)
            {
                DataRow[] drows = changeSetDetailsTable.Select("ChangeSetID = '" + changeSetId + "'");
                foreach (PendingChange item in pendingChangesList)
                {
                    bool isInChangeset = false; ;
                    foreach (DataRow drow in drows)
                    {
                        if (item.ServerItem.Replace(targetBranchServerPath, sourceBranchServerPath).Contains(drow[1].ToString()))
                        {
                            isInChangeset = true;
                            break;
                        }
                    }

                    if (!isInChangeset)
                        deletependingChangesList.Add(item);


                }

                for (int i = 0; i < deletependingChangesList.Count; i++)
                {
                    pendingChangesList.Remove(deletependingChangesList[i]);
                }

                pendingChanges = pendingChangesList.ToArray();


                if (pendingChanges != null && pendingChanges.Length > 0)
                {
                    if (!bulkmergeStarted)
                    {
                        DialogResult dresult = MessageBox.Show("Do you want to check-in pending changes. Dont worry!!! we fill the descriptions automatically", "Check-in", MessageBoxButtons.YesNo);
                        if (dresult == DialogResult.OK || dresult == DialogResult.Yes)
                        {

                            destWorkspace.CheckIn(pendingChanges, comment, null, wrinfo, null);
                            merged = true;
                            mergeLog += changesetToMerge + " Check-in process Done" + "\r\n";

                        }
                        else
                        {
                            mergeLog += "dont forget Check-in" + "\r\n";
                            bulkmergeStarted = false;
                        }
                    }
                    else
                    {
                        destWorkspace.CheckIn(pendingChanges, comment, null, wrinfo, null);
                        merged = true;
                        mergeLog += changesetToMerge + " Check-in process Done" + "\r\n";
                    }
                }
                else
                {
                    mergeLog += changesetToMerge + "Check-in not done. Pending changes is empty." + "\r\n";
                }

            }
            else
            {
                mergeLog += "Please resolve conflicts and do check-in" + "\r\n";
                bulkmergeStarted = false;

                conflicts = destWorkspace.QueryConflicts(new string[] { targetBranchServerPath }, true);
                for (int i = 0; i < conflicts.Length; i++)
                {
                    _conflictsDelegate.Invoke(conflicts[i].ServerPath, false);
                }
            }

            if (_pendingChangesDelegate != null && merged == false && pendingChanges != null && pendingChanges.Length > 0)
            {
                for (int i = 0; i < pendingChanges.Length; i++)
                {
                    _pendingChangesDelegate.Invoke(pendingChanges[i].ServerItem, false, comment, workeditem.Id.ToString());
                }

            }

            if (_loggerDelegate != null)
            {
                _loggerDelegate.DynamicInvoke(mergeLog);
                mergeLog = string.Empty;
            }

            waitingChanges = pendingChanges;
            return merged;

        }

        public bool OnlyCheckIn(string workItemId, string comment, string[] files)
        {
            bool merged = false;

            PendingChange[] pendingChanges = null;
            List<PendingChange> pendingChangesList = waitingChanges.ToList<PendingChange>();
            List<PendingChange> deletependingChangesList = new List<PendingChange>();

            for (int i = 0; i < pendingChangesList.Count; i++)
            {
                if (!files.Contains(pendingChangesList[i].ServerItem))
                    deletependingChangesList.Add(pendingChangesList[i]);
            }

            for (int i = 0; i < deletependingChangesList.Count; i++)
            {
                pendingChangesList.Remove(deletependingChangesList[i]);
            }

            WorkItem workeditem = null;

            for (int t = 0; t < wiCollection.Count; t++)
            {
                if (wiCollection[t].Id.ToString() == workItemId)
                {
                    workeditem = wiCollection[t];
                    break;
                }
            }


            WorkItemCheckinInfo[] wrinfo = new WorkItemCheckinInfo[1];
            wrinfo[0] = new WorkItemCheckinInfo(workeditem, WorkItemCheckinAction.Associate);
            pendingChanges = pendingChangesList.ToArray();


            if (pendingChanges != null && pendingChanges.Length > 0)
            {

                DialogResult dresult = MessageBox.Show("Do you want to check-in pending changes.", "Check-in", MessageBoxButtons.YesNo);
                if (dresult == DialogResult.OK || dresult == DialogResult.Yes)
                {

                    destWorkspace.CheckIn(pendingChanges, comment, null, wrinfo, null);
                    merged = true;
                    mergeLog += " Check-in process Done" + "\r\n";

                }
            }



            if (_loggerDelegate != null)
            {
                _loggerDelegate.DynamicInvoke(mergeLog);
                mergeLog = string.Empty;
            }


            return merged;

        }

        public void StartBulkMerge()
        {
            for (int i = 0; i < mergeTable.Rows.Count; i++)
            {

                if (!bulkmergeStarted)
                {
                    if (_loggerDelegate != null)
                    {
                        _loggerDelegate.DynamicInvoke(".......Process Stopped.......");
                    }
                    break;
                }

                if (mergeTable.Rows[i]["Merged"] != null && mergeTable.Rows[i]["Merged"].ToString() == "True")
                    continue;


                string workItemId = mergeTable.Rows[i][0].ToString();
                string changeSetId = mergeTable.Rows[i][1].ToString();
                string desc = mergeTable.Rows[i][2].ToString();
                bool merged = MergeChangeSet(workItemId, changeSetId, desc, false);
                if (merged)
                    mergeTable.Rows[i]["Merged"] = "True";

            }
            if (_loggerDelegate != null)
            {
                if (bulkmergeStarted)
                    _loggerDelegate.DynamicInvoke(".....................Bulk Merge Process Completed.........................");
                else
                    if (!bulkmergeStarted)
                        _loggerDelegate.DynamicInvoke(".....................Bulk Merge Process Stopped.........................");

            }

            if (bulkmergeStarted)
                MessageBox.Show("Bulk Merge Process Completed.");
            else if (!bulkmergeStarted)
                MessageBox.Show("Bulk Merge Process Stopped.");
        }





        public string tfsUrl
        {
            get;
            set;
        }

        public DataTable mergeTable
        {
            get;
            set;
        }

        public TFSServerList myCustomServerList
        {
            get;
            set;
        }


        public DataTable changeSetDetailsTable
        {
            get;
            set;
        }


        public bool bulkmergeStarted
        {
            get;
            set;
        }

        public string selectedUser
        {
            get;
            set;
        }


        public string selectedProjectName
        {
            get;
            set;
        }

        public DataTable branchTable
        {
            get;
            set;
        }

        public List<string> workItemIDs
        {
            get;
            set;
        }

    }


}
